package com.learn.egweibo666.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.learn.egweibo666.base.response.JsonResult;
import com.learn.egweibo666.base.response.StatusCode;
import com.learn.egweibo666.mapper.UserMapper;
import com.learn.egweibo666.pojo.dto.UserLoginParam;
import com.learn.egweibo666.pojo.dto.UserRegParam;
import com.learn.egweibo666.pojo.entity.User;
import com.learn.egweibo666.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@Api(tags = "用户模块")
@RestController
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "用户注册")
    @ApiOperationSupport(order = 10)
    @PostMapping("/reg")
    public JsonResult reg(@RequestBody @Validated UserRegParam userRegParam){
        log.debug("userRegParam:"+userRegParam);
        String username = userRegParam.getUsername();
        if(userMapper.selectByUsername(username)>0){
            return new JsonResult(StatusCode.USERNAME_EXIST);
        }

        User user = new User();
        BeanUtils.copyProperties(userRegParam,user);
        user.setCreateTime(new Date());
        log.debug("user:"+user);

        int result = userMapper.insertUser(user);
        log.debug(result>1?"注册成功":"注册失败");
        return JsonResult.ok();
    }

    @ApiOperation(value = "用户登录")
    @ApiOperationSupport(order = 20)
    @PostMapping("/login")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session){
        log.debug("用户名：{}，密码：{}",userLoginParam.getUsername(),userLoginParam.getPassword());

        UserVO userVO = userMapper.selectUser(userLoginParam);
        if (userVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        log.debug("userVO" + userVO);
        session.setAttribute("user",userVO);

        return JsonResult.ok();
    }
}
